<?php
namespace app\common\model;

use think\Model;
use think\facade\Env;
use \PHPQRCode\QRcode;
class PHPQrcode extends Model
{

    protected $ext = ['png','jpg','jpeg','gif','wbmp'];

    /**
     * 创建画布
     * @param $width 画布宽度
     * @param $height 画布高度
     * @param $background 画布背景颜色
     * @method createCanvas
     * @author chengzhigang<1256699215@qq.com>
     */
    public function createCanvas($width,$height,$background = array(255,255,255)){
        $canvas = imagecreatetruecolor($width,$height) or die("不能初始化新的 GD 图像流");//创建空白图片
//        $backgroundColor = imagecolorAllocate($canvas, $background[0], $background[1], $background[2]);
//        $backgroundColor = imagecolorallocatealpha($canvas,255,255,255,127);
//        imagecolortransparent($canvas,$backgroundColor);
//        imagefill($canvas, 0, 0, $backgroundColor);
        imagealphablending($canvas, false);
        $transparency = imagecolorallocatealpha($canvas, 0, 0, 0, 127);
        imagefill($canvas, 0, 0, $transparency);
        imagesavealpha($canvas, true);
		return $canvas;
    }

    /**
     * 合并图片
     * @param $dstImage 要合并到的目标图片
     * @param $srcImage 待合并的原始图片
     * @param $dscLeft 合并到目标图片的左边位置
     * @param $dscTop 合并到目标图片的上边位置
     * @param $srcLeft 切割原始图片左边位置
     * @param $srcTop 切割原始图片上边位置
     * @param $dstWidth 切割原始图片宽度
     * @param $dstHeight 切割原始图片高度
     * @param $srcWidth 源图象的宽度
     * @param $srcHeight 源图象的高度
     */
    public function mergeImage($dstImage,$srcImage,$dscLeft,$dscTop,$srcLeft=0,$srcTop=0,$dstWidth,$dstHeight,$srcWidth,$srcHeight){
        imagecopyresampled($dstImage, $srcImage, $dscLeft, $dscTop, $srcLeft,$srcTop, $dstWidth,$dstHeight, $srcWidth, $srcHeight);
    }

    /**
     * 画二维码
     * @param [type] $canvas 画布
     * @param [type] $text 二维码内容
     * @param [type] $left 画布的左边位置
     * @param [type] $top 画布的上边位置
     * @param int $size 二维码大小
     * @param string $level 容错率 L（QR_ECLEVEL_L，7%），M（QR_ECLEVEL_M，15%），Q（QR_ECLEVEL_Q，25%），H（QR_ECLEVEL_H，30%）；
     * @param int $margin 二维码周围边框空白区域间距值
     * @method drawQrcode
     * @author chengzhigang<1256699215@qq.com>
     */
    public function drawQrcode($canvas,$text,$left,$top,$size=4,$level='H',$margin=2,$dstWidth=400,$dstHeight=400){
        $fileName = 'qrcode.png';//临时存储位置（public目录）
        QRcode::png($text,$fileName, $level, $size, $margin);
        $QR = imagecreatefromstring(file_get_contents($fileName));
        $this->mergeImage( $canvas,$QR, $left, $top, 0, 0, $dstWidth, $dstHeight, imagesx($QR), imagesy($QR));
    }

    /**
     * 画logo
     * @param [type] $canvas 画布
     * @param [type] $image 
     * @param $srcLeft 切割原始图片左边位置
     * @param $srcTop 切割原始图片上边位置
     * @param $dstWidth 切割原始图片宽度
     * @param $dstHeight 切割原始图片高度
     * @param $srcWidth 源图象的宽度
     * @param $srcHeight 源图象的高度
     * @method drawImage
     * @author chengzhigang<1256699215@qq.com>
     */
    public function drawImage($canvas,$image,$left=0,$top=0,$dstWidth=0,$dstHeight=0){
        $image = imagecreatefromstring(file_get_contents($image));  //源图象连接资源。
        if($left===false) $left = (imagesx($canvas) * 3 / 8);//logo的宽度(占二维码的1/4)
        if($top===false) $top = $left;
        if(!$dstWidth) $dstWidth = imagesx($image);
        if(!$dstHeight) $dstHeight = imagesy($image);
        $this->mergeImage($canvas, $image, $left, $top, 0, 0, $dstWidth, $dstHeight,imagesx($image), imagesy($image));
        imagedestroy($image);
    }

    /**
     * 画文字
     * @param $canvas 画布
     * @param $text 文本内容
     * @param $fontSize 字体大小
     * @param $color 字体颜色
     * @param $left 画布的左边位置
     * @param $top 画布的上边位置
     * @param $circle 文字的旋转角度
     * @param $width 单行文本长度（解决文本超出画布的情况）
     * @param $font 文字字体
     * @method drawText
     * @author chengzhigang<1256699215@qq.com>
     */
    public function drawText($canvas,$text,$fontSize,$color = array(0,0,0),$left,$top,$circle=0,$width,$spacing=0,$font=false){
        $textColor = imagecolorallocate($canvas, $color[0], $color[1], $color[2]);//为图像分配颜色
        $content = "";
        $lineWidth = 0;
        if(!$font) $font = Env::get('root_path')."public/water/font/font.otf"; //字体类型
        $tempX = $left;
        $textBox = imagettfbbox ($fontSize, $circle, $font, $text);
        for ($i = 0, $j = mb_strlen($text, "utf-8"); $i < $j; $i++) {
            $character = mb_substr($text, $i, 1, "UTF-8");
            if($spacing){
                $textBox = imagettftext($canvas, $fontSize, $circle, $tempX, $top, $textColor, $font,$character);
            }
            if (($lineWidth + $textBox[2]) > $width) {
                $content .= "\n";
                $content .= $character;
                $lineWidth = $textBox[2];
            }
            else {
                $content .= $character;
                $lineWidth += $textBox[2];
            }
            $tempX += $spacing + ($textBox[2] - $textBox[0]);
        }
        if(!$spacing){
            imagettftext($canvas, $fontSize, $circle, $left, $top, $textColor, $font, $content); //将文字写到图片中
        }
    }

    public function drawTextImg($canvas,$text,$fontSize,$color = array(0,0,0),$left,$top,$circle=0,$width,$font=false){
        $textColor = imagecolorallocate($canvas, $color[0], $color[1], $color[2]);//为图像分配颜色
        $content = "";
        $lineWidth = 0;
        if(!$font) $font = Env::get('root_path')."public/water/font/font.otf"; //字体类型
        for ($i = 0, $j = mb_strlen($text, "utf-8"); $i < $j; $i++) {
            $character = mb_substr($text, $i, 1, "UTF-8");
            $textBox = imagettfbbox($fontSize, $circle, $font, $character);
            if (($lineWidth + $textBox[2]) > $width) {
                $content .= "\n";
                $content .= $character;
                $lineWidth = $textBox[2];
            }
            else {
                $content .= $character;
                $lineWidth += $textBox[2];
            }
        }
        imagettftext($canvas, $fontSize, $circle, $left, $top, $textColor, $font, $content); //将文字写到图片中
    }

    /**
     * 输出二维码
     * @param [type] $canvas
     * @param [type] $saveName
     * @method outputQrcode
     * @author chengzhigang<1256699215@qq.com>
     */
    public function outputQrcode($canvas,$saveName){
        if (!is_dir(dirname($saveName))) {
            mkdir(dirname($saveName), 0755, true);
        }
        $extension = strtolower(pathinfo($saveName, PATHINFO_EXTENSION));
        in_array($extension,$this->ext) or die('不支持的图片后缀');
        $this->downImage($extension,$canvas,$saveName);
//        imagepng($canvas,$saveName);
        imagedestroy($canvas);
    }

    /**
     * 生成新图片
     * @param [type] $extension
     * @param [type] $canvas
     * @param [type] $saveName
     * @method downImage
     * @author chengzhigang<1256699215@qq.com>
     */
    private static function downImage($extension,$canvas,$saveName){
        switch($extension){
            case 'png':
                imagepng($canvas,$saveName);
                break;
            case 'jpg':
                imagejpeg($canvas,$saveName);
                break;
            case 'jpeg':
                imagejpeg($canvas,$saveName);
                break;
            case 'gif':
                imagegif($canvas,$saveName);
                break;
            case 'wbmp':
                imagewbmp($canvas,$saveName);
                break;
            default:
//                die('不支持的图片后缀');
                break;
        }
    }

}